package net.oschina.app.ui;

import android.graphics.Color;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.jcodecraeer.xrecyclerview.XRecyclerView;

import net.oschina.app.BuildConfig;
import net.oschina.app.MApp;
import net.oschina.app.R;
import net.oschina.app.adapter.FriendCircleAdapter;
import net.oschina.app.bean.Active;
import net.oschina.app.bean.ActiveList;
import net.oschina.app.interf.OnRecycleViewItemClickListener;
import net.oschina.app.util.PreferencesUtils;
import net.oschina.app.util.XmlUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static net.oschina.app.MApp.mContext;
import static net.oschina.app.MApp.mHandler;

/**
 * Created by huang on 2017-4-1.
 * 好友圈页面
 */

public class FriendCircleActivity extends AppCompatActivity {
    private Toolbar mToolbar;
    private XRecyclerView mRvFriendCircle;
    private List<Active> mActiveList = new ArrayList<>();
    private int page = 0;
    private FriendCircleAdapter mFriendCircleAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        initData();
        initEvent();

    }

    @NonNull
    private void initView() {
        setContentView(R.layout.activity_friend_circle);
        mToolbar = (Toolbar) findViewById(R.id.tb_friend_circle);
        setSupportActionBar(mToolbar);
        mToolbar.setNavigationIcon(R.drawable.actionbar_back_icon_normal);
        mRvFriendCircle = (XRecyclerView) findViewById(R.id.rv_friend_circle);//XRecyclerView

    }

    //初始化数据
    private void initData() {
        //设置布局管理器
        final LinearLayoutManager manager = new LinearLayoutManager(this);
        mRvFriendCircle.setLayoutManager(manager);

        //网络加载数据
        OkHttpClient client = new OkHttpClient();
        String url = "http://10.0.2.2:8080/oschina/list/active_list1/page" + page + ".xml";
        Request.Builder builder = new Request.Builder().url(url);
        Request request = builder.build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                byte[] bytes = response.body().bytes();
                ActiveList list = XmlUtils.toBean(ActiveList.class, bytes);
                //获取bean类数据
                mActiveList = list.getActivelist();
                if (mActiveList != null) {
                    page++;
                }
                runOnUiThread(new Runnable() {//运行在主线程
                    @Override
                    public void run() {
                        mFriendCircleAdapter = new FriendCircleAdapter(mContext, mActiveList);
                        //设置适配器
                        mRvFriendCircle.setAdapter(mFriendCircleAdapter);
                        //条目点击监听
                        initItemClick();
                    }
                });
            }
        });
    }

    //条目点击监听
    private void initItemClick() {
        //监听条目点击事件
        mFriendCircleAdapter.setOnItemClickListener(new OnRecycleViewItemClickListener() {
            @Override
            public void onClick(View view, int position) {
                //保存条目点击状态
                saveItemState(view, position);

            }
        });
    }

    //保存条目点击状态
    private void saveItemState(View view, int position) {
        //保存条目点击的状态
        Active active = mActiveList.get(position - 1);
        String id = String.valueOf(active.getId());//获取点击条目数据的id
        String ids = PreferencesUtils.getString(MApp.mContext, "fcItem_isRead", "");//获取已保存的id
        if (!ids.contains(id)) {//已保存的id不包含点击条目数据的id
            ids += id;//添加条目数据id到sp
            PreferencesUtils.putString(MApp.mContext, "fcItem_isRead", ids);
        }

        //设置点击后控件的颜色
        TextView tvObjectTitle = (TextView) view.findViewById(R.id.tv_friend_circle_objecttitle);
        TextView tvMessage = (TextView) view.findViewById(R.id.tv_friend_circle_message);
        tvObjectTitle.setTextColor(Color.parseColor("#ADAAAD"));
        tvMessage.setTextColor(Color.parseColor("#ADAAAD"));
    }

    //初始化事件
    private void initEvent() {
        //监听toolBar导航图标(返回图标)
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //销毁本activity
                finish();
            }
        });

        //监听刷新和加载更多
        mRvFriendCircle.setPullRefreshEnabled(true);
        mRvFriendCircle.setLoadingMoreEnabled(true);
        mRvFriendCircle.setLoadingListener(new XRecyclerView.LoadingListener() {
            //下拉刷新
            @Override
            public void onRefresh() {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mRvFriendCircle.refreshComplete();
                        Toast.makeText(FriendCircleActivity.this, "刷新完成", Toast.LENGTH_SHORT).show();
                    }
                }, 1000);
            }

            //上拉加载更多
            @Override
            public void onLoadMore() {
                OkHttpClient client = new OkHttpClient();
                String url = "http://10.0.2.2:8080/oschina/list/active_list1/page" + page + ".xml";
                Request.Builder builder = new Request.Builder().url(url);
                Request request = builder.build();
                Call call = client.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        byte[] bytes = response.body().bytes();
                        ActiveList list = XmlUtils.toBean(ActiveList.class, bytes);
                        if (list != null) {
                            //获取bean类数据
                            mActiveList.addAll(list.getActivelist());
                            page++;
                            if (BuildConfig.DEBUG) Log.d("加载更多", "page:" + page);
                            SystemClock.sleep(1000);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    mFriendCircleAdapter.notifyDataSetChanged();
                                    mRvFriendCircle.loadMoreComplete();
                                }
                            });
                        } else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    mRvFriendCircle.setNoMore(true);
                                }
                            });
                        }
                    }
                });
            }
        });
    }
}
